package com.junjie.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
    //生成
    private static final String SIGNATURE = "YiJunJie";

    //生成 Token  Header, payload, signature
    public static String getToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, 1);//指定 1 个小时之后过期
        //创建 JWT 的 builder
        JWTCreator.Builder builder = JWT.create();
        //payload  使用lambda表达式对map进行遍历
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        //指定令牌过期时间, 签名 里面放密钥(盐值)
        String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SIGNATURE));
        return token;
    }

    //验证 Token 没有抛出异常验证就通过
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    //获取 Token 中 keyName 对应的值
    public static String getTokenStringValue(String token, String keyName) {
        return getTokenInfo(token).getClaim(keyName).asString();
    }

    //获取 Token 中 keyName 对应的值
    public static int getTokenIntValue(String token, String keyName) {
        return getTokenInfo(token).getClaim(keyName).asInt();
    }

    //获取 Token 信息的方法
    public static DecodedJWT getTokenInfo(String token) {
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    /*JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("yijunjie")).build();
    验证并获取信息
    DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6IuWwj-m7kSIsImV4cCI6MTU5OTQ2ODEzMywidXNlcklkIjoxfQ.wwOzREUgICVb7lx0BQsnBU-vFtGSIYGy4yOb9UAEJh4");
    打印获取的信息
    System.out.println(verify.getClaim("userId").asInt());
    System.out.println(verify.getClaim("userName").asString());
    获取令牌的过期时间(如果过期的话会抛出 TokenExpiredException 异常)
    System.out.println(verify.getExpiresAt());*/
}
